package com.scalar.chiptrack.finance.openpo.actioncommands;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.finance.openpo.PurchaseOrder;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItem;
import com.scalar.chiptrack.finance.openpo.PurchaseOrderLineItemList;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;
import com.scalar.chiptrack.finance.openpo.forms.OpenPurchaseOrderForm;
import com.scalar.chiptrack.finance.openpo.forms.PurchaseOrderForm;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;

/**
 * Author: Phani Raja Kumar
 * Date  : Feb 17, 2005
 * Time  : 11:20:31 AM
 */
public class PurchaseOrderNewCommand extends ChipTrackExtendedAction
{
    public ActionForward executeRequest( ActionMapping mapping,
                                         ActionForm form,
                                         HttpServletRequest request,
                                         HttpServletResponse response ) throws Exception
    {

        HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );
        PurchaseOrderForm purchaseOrderForm = ( PurchaseOrderForm ) form;
		String actionForward 		= "Search";
        HttpSession mSession 		= request.getSession();
        int purchaseOrderType       = 0;
        PurchaseOrderLineItem purchaseOrderLineItem = new PurchaseOrderLineItem();
        String poNumber                             = "";
        PurchaseOrderLineItemList purchaseOrderLineItemList = new PurchaseOrderLineItemList();
        Date date                                   = new Date();
		try
        {
            resetPurchaseOrderForm( purchaseOrderForm );
            purchaseOrderType = Integer.parseInt( request.getParameter("poType") );
            if ( purchaseOrderType == PurchaseOrder.Purchase_Order_Type_Open )
            {
                actionForward = "NewOpenPO";
            }
            else if ( ( purchaseOrderType == PurchaseOrder.Purchase_Order_Type_Standard ) || ( purchaseOrderType == PurchaseOrder.Purchase_Order_Type_DropShip ) )
            {
                if( purchaseOrderForm.getOpenPurchaseOrder_Id() == -1 )
                {
                    purchaseOrderForm.setOpenPurchaseOrderNumber("");
                    poNumber = PurchaseOrderDAO.loadAutomatedPurchaseOrderNo();
                    purchaseOrderForm.setPurchaseOrderNumber( poNumber );
                }

                purchaseOrderForm.setPurchaseOrderDate( StringUtils.formatDateToString( date, "MM/dd/yyyy" ) );
                purchaseOrderForm.setBillingAddress( PurchaseOrderDAO.getClientAddress() );
                purchaseOrderForm.setBillingAddress_id( PurchaseOrderDAO.getClientAddress().getAddressId() );
                // If the Purchase Order Is created From an Open PO then Load the Shipping Address from Open PO
                if( purchaseOrderForm.getOpenPurchaseOrder_Id() != -1 )
                {
					OpenPurchaseOrderForm openPurchaseOrderForm = new OpenPurchaseOrderForm();
					openPurchaseOrderForm.setPurchaseOrder_id( purchaseOrderForm.getOpenPurchaseOrder_Id() );

					PurchaseOrderDAO.loadOpenPurchaseOrder( openPurchaseOrderForm );
                    poNumber = PurchaseOrderDAO.loadAutomatedPurchaseOrderNoByOpenPurchaseOrderNo( openPurchaseOrderForm );
                    purchaseOrderForm.setPurchaseOrderNumber( poNumber );
					purchaseOrderForm.setOpenPurchaseOrderNumber( openPurchaseOrderForm.getPoNumber() );
					purchaseOrderForm.setVendorName( openPurchaseOrderForm.getVendorName() );
					purchaseOrderForm.setShippingAddress_id( openPurchaseOrderForm.getShippingAddress_id() );
					purchaseOrderForm.setShippingAddress( PurchaseOrderDAO.getAddress( purchaseOrderForm.getShippingAddress_id() ) );
					purchaseOrderForm.setRemainingOpenPOAmt( openPurchaseOrderForm.getPoRemainingAmt() );

                    purchaseOrderForm.setVendorQuoteNumber( openPurchaseOrderForm.getVendorQuoteNumber());

                    //start: added by Murali Krishna, set the holds to approved by default if the purchase order if created from open po
                    purchaseOrderLineItem.setFinanceHold(0);
                    purchaseOrderLineItem.setOperationsHold(0);
                    //end: Murali Krishna

                    request.setAttribute("searchType", "OpenPOSearch");
                }
                else
                {
					PurchaseOrderDAO.setVendorNameAndShippingAddresses( purchaseOrderForm );
                    request.setAttribute("searchType", "Generate");
                }
                purchaseOrderForm.setShippingMethodsList( NewCustomerDAO.loadAllShippingMethods ( null, -1 ) );
                purchaseOrderForm.setPayTermsList( SalesDAO.getAllShippingTerms() );
                purchaseOrderLineItem.setStatus( Constants.PURCHASE_ORDER_STATUS_NEW );
                purchaseOrderLineItemList.add( purchaseOrderLineItem );



                purchaseOrderForm.setPurchaseOrderLineItemList( purchaseOrderLineItemList );

                request.setAttribute( "purchaseOrderTypesList", PurchaseOrderDAO.loadPurchaseOrderTypes() );
                request.setAttribute( "processNameList", PurchaseOrderDAO.loadProcessNames( purchaseOrderForm.getVendor_id() ) );
                request.setAttribute( "packageTypeList", PurchaseOrderDAO.loadPackageTypeList() );
                request.setAttribute( "financeReasonCodes", PurchaseOrderDAO.loadFinanceHolds() );
                request.setAttribute( "opsReasonCodes", PurchaseOrderDAO.loadOperationsHolds() );
                request.setAttribute( "poTaxes", PurchaseOrderDAO.loadPOTaxesList () );


                actionForward = "NewManufacturingPO";
            }
       	}
        catch ( Exception e )
        {
            Logger.error( ERROR_COULD_NOT_CREATE_PURCHASE_ORDER_INSTANCE, e );
            errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_COULD_NOT_CREATE_PURCHASE_ORDER_INSTANCE );
			mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( ERROR_COULD_NOT_CREATE_PURCHASE_ORDER_INSTANCE, e ) );
            actionForward = "Search";
        }

		request.setAttribute( ERROR_MESSAGES, errors );
		request.setAttribute( INFO_MESSAGES, info );
		return mapping.findForward( actionForward );
    }

    private void resetPurchaseOrderForm(PurchaseOrderForm purchaseOrderForm)
    {
        purchaseOrderForm.setPurchaseOrder_Id( -1 ) ;
        purchaseOrderForm.setVendorName( "" );
        purchaseOrderForm.setVendorQuoteNumber( "" ) ;
		purchaseOrderForm.setSubTotal( 0.0 );
		purchaseOrderForm.setFreight( 0.0 );
		purchaseOrderForm.setTradeDiscount( 0.0 );
		purchaseOrderForm.setMiscellaneous( 0.0 );
		purchaseOrderForm.setTax( 0.0 );
        purchaseOrderForm.setTotal( 0.0 );
        purchaseOrderForm.setPoTaxType( "0" );

        purchaseOrderForm.setShippingMethodId( -1 );
        purchaseOrderForm.setShipMethod( null );
        purchaseOrderForm.setNewShippingAccount( "" );
        purchaseOrderForm.setNewShippingMethod( "" );
        purchaseOrderForm.setPayTerms( "" );
        purchaseOrderForm.setNewPayTerms( "" );
        purchaseOrderForm.setValidToDate( "" );

    }
}